<template>
    <div class="platform">
        <my-tag title="发布作品" :showSortImg="false"></my-tag>
        <div class="platform-box">
            <el-form ref="editSchemRef" :model="editSchemForm" :rules="rules" label-width="auto" label-position="top"
                class="demo-ruleForm platform-formList">
                <div class="form-left-six">
                    <el-form-item label="设计师昵称：" prop="decorDesignerId">
                        <el-select v-model="editSchemForm.decorDesignerId" filterable placeholder="请输入或选择设计师昵称"
                            size="large">
                            <el-option v-for="item in designerListData" :key="item.designerId" :label="item.designerName"
                                :value="item.designerId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="作品名称" prop="schemeName">
                        <el-input v-model="editSchemForm.schemeName" @focus="editSchemFormLimit.schemeNameLimit = true"
                            @blur="editSchemFormLimit.schemeNameLimit = false"
                            :show-word-limit="editSchemFormLimit.schemeNameLimit" maxlength="20" placeholder="请输入作品名称" />
                    </el-form-item>
                    <el-form-item label="小区名称" prop="address">
                        <el-input v-model="editSchemForm.address" @focus="editSchemFormLimit.addressLimit = true"
                            @blur="editSchemFormLimit.addressLimit = false"
                            :show-word-limit="editSchemFormLimit.addressLimit" maxlength="15" placeholder="请输入小区名称" />
                    </el-form-item>
                    <el-form-item label="设计理念" prop="designIdea">
                        <el-input type="textarea" :autosize="{ minRows: 8 }" v-model="editSchemForm.designIdea"
                            placeholder="请输入设计说明，详细的说明会得到更多认可" @focus="editSchemFormLimit.remarkLimit = true"
                            @blur="editSchemFormLimit.remarkLimit = false" :show-word-limit="editSchemFormLimit.remarkLimit"
                            maxlength="500" />
                    </el-form-item>
                    <el-form-item label="户型图" prop="layoutIds">
                        <image-upload v-model="editSchemForm.layoutIds" :limit="1" />
                    </el-form-item>
                    <el-form-item label="房间区域相册">
                        <el-table :data="roomAreaList">
                            <el-table-column>
                                <template #default="scope">
                                    <div class="room-space">
                                        <div class="space-title">
                                            <div class="title">
                                                <div @click="chooseSpaceRoom(scope.$index, scope.row.classTypeId)">区域类型：{{
                                                    scope.row.classTypeId
                                                    === '' ?
                                                    '请选择区域类型' :
                                                    getValueById(scope.row.classTypeId)
                                                }}</div>
                                            </div>
                                            <div class="title">
                                                区域名称：<el-input v-model="scope.row.schemName" style="width:70%;"
                                                    @focus="scope.row.schemNameLimit = true"
                                                    @blur="scope.row.schemNameLimit = false"
                                                    :show-word-limit="scope.row.schemNameLimit" maxlength="10"
                                                    placeholder="请输入区域具体的名称" />
                                            </div>
                                            <div class="icon" @click="delSpaceRoom(scope.$index)">删 除</div>
                                        </div>
                                        <div class="space-img">
                                            <image-upload v-model="scope.row.schemImgId" :limit="5" />
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="add-room" @click="addSpaceRoom">+ 添加房间</div>
                    </el-form-item>
                </div>
                <div class="form-right-four">
                    <el-form-item label="封面图片" prop="coverImage">
                        <div class="coverImg-style">
                            <image-upload v-model="editSchemForm.coverImage" :limit="1" :showAddIcon="false">
                                <div>上传作品封面图</div>
                                <div style="font-size: 12px;color: #ACB3BD;line-height: 18px;">建议图片尺寸320*244px</div>
                            </image-upload>
                        </div>
                    </el-form-item>
                    <el-form-item label="面积(㎡)" prop="area">
                        <el-input-number style="width:100%;" v-model="editSchemForm.area" :min="1" :max="999999"
                            controls-position="right" size="default" placeholder="请输入施工面积"></el-input-number>
                    </el-form-item>
                    <div style="display:flex;width:100%;min-width: 500px;align-items:center">
                        <el-form-item label="参考预算价(万元)：" prop="priceLower" style="width:30%;">
                            <el-input-number controls-position="right" class="my-el-input-number" size="default"
                                placeholder="最底参考预算价" v-model="editSchemForm.priceLower" :precision="2" :step="1"
                                :min="0.01" :max="999" style="width:100%" />
                        </el-form-item>
                        <div style="padding: 0 10px;line-height: 90px;">~</div>
                        <el-form-item label="" prop="priceUpper" style="width:30%;margin-top: 24px;">
                            <el-input-number controls-position="right" class="my-el-input-number" size="default"
                                placeholder="最高参考预算价" v-model="editSchemForm.priceUpper" :precision="2" :step="1"
                                :min="editSchemForm.priceLower" :max="999" style="width:100%" />
                        </el-form-item>
                    </div>
                    <el-form-item label="户型" prop="hoseType">
                        <div class="hoseType">
                            <div class="hoseType-box">
                                <el-form-item prop="bedrooms" style="width:100%">
                                    <el-select v-model="editSchemForm.bedrooms" size="large">
                                        <el-option v-for="item in hoseTypeSel" :key="item.id" :label="item.value"
                                            :value="item.id" />
                                    </el-select>
                                </el-form-item>
                                <div class="unit">室</div>
                            </div>
                            <div class="hoseType-box">
                                <el-form-item prop="livingRooms" style="width:100%">
                                    <el-select v-model="editSchemForm.livingRooms" size="large">
                                        <el-option v-for="item in hoseTypeSel" :key="item.id" :label="item.value"
                                            :value="item.id" />
                                    </el-select>
                                </el-form-item>
                                <div class="unit">厅</div>
                            </div>
                            <div class="hoseType-box">
                                <el-form-item prop="bathrooms" style="width:100%">
                                    <el-select v-model="editSchemForm.bathrooms" size="large">
                                        <el-option v-for="item in hoseTypeSel" :key="item.id" :label="item.value"
                                            :value="item.id" />
                                    </el-select>
                                </el-form-item>
                                <div class="unit">卫</div>
                            </div>
                            <div class="hoseType-box">
                                <el-form-item prop="kitchens" style="width:100%">
                                    <el-select v-model="editSchemForm.kitchens" size="large">
                                        <el-option v-for="item in hoseTypeSel" :key="item.id" :label="item.value"
                                            :value="item.id" />
                                    </el-select>
                                </el-form-item>
                                <div class="unit">厨</div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="风格" prop="style">
                        <el-check-tag v-for="item in styleSel" :key="item.classId"
                            :checked="item.classId === styleId ? true : false" size="large"
                            @click="selectStyle(item.classId, item.className)">
                            {{ item.className }}
                        </el-check-tag>
                    </el-form-item>
                </div>
            </el-form>

            <div class="footer-btn" style="padding-bottom:20px;">
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">提 交</el-button>
                    <el-button @click="cancel">返 回</el-button>
                </div>
            </div>
        </div>
        <el-dialog title="选择空间" v-model="spaceRoomVisible" center>
            <div>
                <el-check-tag v-for="item in roomSpaceType" :key="item.classId"
                    :checked="item.classId === spaceChooseId ? true : false" size="large"
                    @click="selectSpaceType(item.classId, item.className)">
                    {{ item.className }}
                </el-check-tag>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { getSchem, addSchem, updateSchem, getRoomType } from "@/api/decor/schem";
import { listDesigner, getImgUrl } from "@/api/decor/designer";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
// 设计师下拉数据
const designerListData = ref([])

let spaceRoomVisible = ref(false)
// 获取风格的下拉框
const styleSel = ref([])

let clickIndex = ref(-1)
// 弹框
let open = ref(false)
// 选中的空间
let spaceChooseId = ref(-1)
// 选中的风格
let styleId = ref(-1)
// 户型
const hoseTypeSel = ref([
    { id: 1, value: 1 },
    { id: 2, value: 2 },
    { id: 3, value: 3 },
    { id: 4, value: 4 },
    { id: 5, value: 5 },
    { id: 6, value: 6 },
    { id: 7, value: 7 },
    { id: 8, value: 8 },
    { id: 9, value: 9 },
    { id: 10, value: 10 },
])
let spaceChooseName = ref('')
// 获取房间空间
let roomSpaceType = ref([])
// 房间区域相册列表
let roomAreaList = ref([
    { schemName: '客厅', classTypeId: "163482314629677056", schemImgId: '', schemNameLimit: false },
    { schemName: '餐厅', classTypeId: "163482636454428672", schemImgId: '', schemNameLimit: false },
    { schemName: '主卧', classTypeId: "163483252459274240", schemImgId: '', schemNameLimit: false },
    { schemName: '厨房', classTypeId: "163483011299377152", schemImgId: '', schemNameLimit: false },
    { schemName: "卫生间", classTypeId: "163483112327577600", schemImgId: '', schemNameLimit: false }
])
const data = reactive({
    editSchemForm: {},
    editSchemFormLimit: {
        designerNameLimit: false,
        addressLimit: false,
        schemeNameLimit: false,
        houseTypeLimit: false,
        styleLimit: false,
        areaLimit: false,
        designIdeaLimit: false,
        remarkLimit: false,
    },
    rules: {
        decorDesignerId: [{ required: true, message: "请选择设计师昵称", trigger: "blur" }],
        coverImage: [
            { required: true, message: "请上传封面图", trigger: "blur" }
        ],
        layoutIds: [{ required: true, message: "请上传户型图", trigger: "blur" }],
        designerName: [
            { required: true, message: "设计师昵称不能为空", trigger: "blur" },
        ],
        schemeName: [
            { required: true, message: "方案名称不能为空", trigger: "blur" }
        ],
        address: [
            { required: true, message: "小区名称不能为空", trigger: "blur" }
        ],
        area: [
            { required: true, message: "面积不能为空", trigger: "blur" }
        ],
        houseType: [
            { required: true, message: "户型不能为空", trigger: "blur" }
        ],
        style: [
            { required: true, message: "风格不能为空", trigger: "blur" }
        ],
        livingRooms: [{ required: true, message: "客厅数量不能为空", trigger: "blur" }],
        bedrooms: [{ required: true, message: "房间数量不能为空", trigger: "blur" }],
        bathrooms: [{ required: true, message: "卫生间数量不能为空", trigger: "blur" }],
        kitchens: [{ required: true, message: "厨房数量不能为空", trigger: "blur" }],
        priceUpper: [{ required: true, message: "最高参考预算价不能为空", trigger: "blur" }],
        priceLower: [{ required: true, message: "最低参考预算价不能为空", trigger: "blur" }],
    },
    dialogForm: {},
    rulesDialog: {
        schemImg: [{ required: true, message: "请上传区域图", trigger: "blur" }]
    }
});

const { editSchemForm, editSchemFormLimit, rules, dialogForm, rulesDialog } = toRefs(data);
// 获取设计方案详情信息
(() => {
    const schemeId = route.params.schemeId
    if (schemeId) {
        getSchem(schemeId).then((res) => {
            editSchemForm.value = res.data
            editSchemForm.value.priceUpper = parseFloat(res.data.priceUpper) / 10000
            editSchemForm.value.priceLower = parseFloat(res.data.priceLower) / 10000
            editSchemForm.value.area = parseFloat(res.data.area)
            let _temp = []
            let imgUrlPromises = [];
            res.data.schemDetails.forEach((v) => {
                if (v.schemImgId) {
                    let promise = getImgUrl(v.schemImgId).then((res) => {
                        _temp.push({
                            schemName: v.schemName,
                            schemImgId: v.schemImgId,
                            classTypeId: v.classTypeId,
                            schemDetailId: v.schemDetailId,
                            version: v.version,
                            schemImgUrl: res.data,
                        });
                    });
                    imgUrlPromises.push(promise);
                }
            })
            // 等待所有图片 URL 获取完成
            Promise.all(imgUrlPromises).then(() => {
                // 所有异步操作完成后再进行后续处理
                roomAreaList.value = _temp
            });
        })
    }
})();
// 根据id拿到value
const getValueById = (classTypeId) => {
    let detail = roomSpaceType.value.find((value) => value.classId === classTypeId)
    return detail ? detail.className : ''
}
// 获取设计师下拉列表数据
const getDesignerList = () => {
    listDesigner({
        designerStatus: 1,
    }).then((res) => {
        designerListData.value = res.rows
    })
}
// 获取房间空间
const getSpaceRoomType = () => {
    getRoomType({ className: '空间' }).then((res) => {
        roomSpaceType.value = res.data[0].childrenNode
    })
    getRoomType({ className: '风格' }).then((res) => {
        styleSel.value = res.data[0].childrenNode
    })
}
const selectStyle = (id, className) => {
    styleId.value = id
    editSchemForm.value.style = className
}
// 添加房间按钮
const addSpaceRoom = () => {
    roomAreaList.value.push({ schemName: '', classTypeId: '', schemImgId: '', schemNameLimit: false })
}
// 选择空间按钮
const chooseSpaceRoom = (index, classTypeId) => {
    spaceRoomVisible.value = true
    clickIndex.value = index
    spaceChooseId.value = classTypeId
}
// 弹框选择空间
const selectSpaceType = (id, name) => {
    spaceChooseName.value = name
    spaceChooseId.value = id
    roomAreaList.value[clickIndex.value].classTypeId = id
    spaceRoomVisible.value = false
}
// 删除房间按钮
const delSpaceRoom = (index) => {
    roomAreaList.value.splice(index, 1)
}
// 提交按钮
function submitForm() {
    proxy.$refs["editSchemRef"].validate(valid => {
        if (valid) {
            // classTypeId是否为空
            const hasEmptyClassTypeId = roomAreaList.value.some(item => item.classTypeId === '' || item.classTypeId === null);
            // schemImgId是否为空
            const hasEmptySchemImgId = roomAreaList.value.some(item => item.schemImgId === '' || item.schemImgId === null);
            const hasEmptySchemName = roomAreaList.value.some(item => item.schemName === '' || item.schemName === null);
            if (hasEmptyClassTypeId) {
                proxy.$modal.msgError("请选择房间区域相册中的区域类型");
                return
            }
            if (hasEmptySchemImgId) {
                proxy.$modal.msgError("已选择的区域类型应至少有一张区域图");
                return
            }
            if (hasEmptySchemName) {
                proxy.$modal.msgError("请完善已选择区域类型中具体的区域名称");
                return
            }
            let decorSchemDetailBoList = []
            roomAreaList.value.forEach((v) => {
                let detailId = v.schemDetailId;
                if (detailId) {
                    decorSchemDetailBoList.push({
                        schemName: v.schemName,
                        classTypeId: v.classTypeId,
                        schemImgId: v.schemImgId,
                        schemDetailId: v.schemDetailId,
                        version: v.version
                    })
                } else {
                    decorSchemDetailBoList.push({
                        schemName: v.schemName,
                        classTypeId: v.classTypeId,
                        schemImgId: v.schemImgId,
                    })
                }
            })
            const data = {
                decorSchemBo: {
                    ...editSchemForm.value,
                    priceUpper: parseFloat(editSchemForm.value.priceUpper) * 10000,
                    priceLower: parseFloat(editSchemForm.value.priceLower) * 10000,
                    schemStatus: 1

                },
                decorSchemDetailBoList: decorSchemDetailBoList
            }
            if (editSchemForm.value.schemeId != null) {
                updateSchem(data).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    router.go(-1)
                });
            } else {
                addSchem(data).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    router.go(-1)
                });
            }
        } else {
            proxy.$modal.msgError('请根据提示完善必填信息')
        }
    });
}
// 返回
const cancel = () => {
    router.go(-1)
}
getDesignerList()
getSpaceRoomType()
</script>
<style lang="scss" scoped>
.hoseType {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    .hoseType-box {
        width: 30%;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .unit {
            font-family: NotoSansHans, NotoSansHans;
            font-weight: 600;
            font-size: 14px;
            color: #000000;
            line-height: 21px;
            font-style: normal;
            padding: 0 4px 0 4px;
        }
    }
}

.coverImg-style {
    width: 100%;

    ::v-deep(.el-upload-list--picture-card) {
        width: 320px;
        height: 240px;
    }

    ::v-deep(.el-upload--picture-card) {
        width: 320px;
        height: 240px;
    }

    ::v-deep(.el-upload-list--picture-card .el-upload-list__item) {
        width: 320px;
        height: 240px;
        border-radius: 8px;
        border: 1px solid #CDD4E0;
    }

}

::v-deep(.el-table) {
    border: none !important;
}

::v-deep(.el-table .cell) {
    padding: 0;
}

::v-deep(.el-table .el-table__cell) {
    padding: 0;
}

::v-deep(.el-table .el-table__header-wrapper th, .el-table .el-table__fixed-header-wrapper th) {
    height: 0 !important;
    background-color: transparent !important;
}

::v-deep(.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf) {
    border-bottom: none;
}
</style>